package com.manager.common.interceptor;

import com.manager.common.token.TokenManager;
import com.manager.common.token.TokenUtils;
import com.manager.common.vo.ResultVO;
import com.manager.common.constant.ResultVOEnum;
import com.manager.model.System_User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Enumeration;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        //   response.setHeader("Access-Control-Allow-Headers", "satoken,access-control-allow-origin, authority, content-type, version-info, X-Requested-With");

        String uri = request.getRequestURI();
        logger.info("uri:{}",uri);
        if(uri.contains("/login") || uri.contains("/assets") || uri.contains("/uploadFiles")
                || uri.contains("/mergeFile") || uri.endsWith("/index") || uri.contains("/exportExcelDatas")
            || uri.contains("/receipt") ){
            return true;
        }
        String downloadToken = request.getParameter("downToken");
        if(StringUtils.isNotEmpty(downloadToken) && TokenManager.getInstance().hasDownloadToken(downloadToken)){
            return true;
        }
        if(uri.endsWith("/error")){
            response.sendRedirect(request.getContextPath()+"/index");
            return true;
        }
        if(TokenManager.getInstance().isLogin()){
            try {
                System_User user = TokenManager.getInstance().get(TokenUtils.getCurrentToken());
                if(user == null){
                    response.getWriter().write(ResultVO.failed(ResultVOEnum.SESSION_TIME_OUT).toString());
                    response.getWriter().flush();
                    return false;
                }
            }catch (Exception e){
                response.getWriter().write(ResultVO.failed(ResultVOEnum.SESSION_TIME_OUT).toString());
                response.getWriter().flush();
            }
            return true;
        }
        response.getWriter().write(ResultVO.failed(ResultVOEnum.SESSION_TIME_OUT).toString());
        response.getWriter().flush();
        return false;
    }
}
